package com.honry.common.spring;

import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryDelegatingImpl;

public class SpringHibernateSessionProvider {
	private static final ThreadLocal<Session> sessionHolder =new ThreadLocal<Session>();
	private SessionFactory sessionFactory;
	public SpringHibernateSessionProvider() {
		
	}
	public Connection connection(){
		Connection connection=null;
		
		try {
			SessionFactoryDelegatingImpl sfi=(SessionFactoryDelegatingImpl)sessionFactory;
			connection =sfi.getJdbcServices().getBootstrapJdbcConnectionAccess().obtainConnection();
			
		} catch (SQLException e) {
			throw new IllegalStateException(
                    "无法从session factory获取联接:"
                    + e.getMessage(),
                    e);
		}
		return connection;
	}
	public Session session(){
		Session threadBoundSession=sessionHolder.get();
		if(threadBoundSession==null){
			try {
				threadBoundSession = this.sessionFactory.getCurrentSession();
			} catch (Exception e) {
				threadBoundSession = this.sessionFactory.openSession();
			}
			boolean isopen = threadBoundSession.isOpen();
			sessionHolder.set(threadBoundSession);
		}
		return threadBoundSession;
	}
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory=sessionFactory;
	}
}
